﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Runtime.InteropServices;


namespace vm_controller
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>


    public partial class App : Application
    {
        //声明默认配置文件路径
        public string INIPath = Convert.ToString(System.AppDomain.CurrentDomain.BaseDirectory) + "config.ini";

        System.Threading.Mutex mutex;

        IniFiles ConfigINI = new IniFiles();

        public App()
        {
            this.Startup += new StartupEventHandler(App_Startup);
        }

        void App_Startup(object sender, StartupEventArgs e)
        {
            //MessageBox.Show("已有一个程序实例运行");
            bool ret;
            mutex = new System.Threading.Mutex(true, "vm_controller", out ret);

            if (!ret)
            {
                string windowName = ConfigINI.INIRead("window", "name", INIPath);
                //MessageBox.Show("已有一个程序实例运行");
                IntPtr winHanle = FindWindow(null, windowName);
                _ = ShowWindow(winHanle, 2);
                System.Threading.Thread.Sleep(100);
                _ = ShowWindow(winHanle, 3);
                Environment.Exit(0);
            }

        }
        #region API 需要using System.Runtime.InteropServices;

        [DllImport("user32.dll")]
        public static extern IntPtr FindWindow(string lpszClass, string lpszWindow);      //按照窗体类名或窗体标题查找窗体

        [DllImport("user32.dll", EntryPoint = "ShowWindow", CharSet = CharSet.Auto)]
        private static extern int ShowWindow(IntPtr hwnd, int nCmdShow);                  //设置窗体属性

        #endregion
    }
}
